<template>
  <div class="f_div">
    <div class="t_div">设置 / <a href="#">企业信息</a></div>
    <el-container>
      <el-header class="header"
        ><div class="h_div">
          <div class="h_in_vid">企业信息</div>
        </div></el-header
      >
      <el-main class="main">
        <el-form
          style="max-width: 600px"
          :model="info_Company"
          label-width="auto"
          ref="form"
          :rules="rules"
          status-icon
          accept=".jpg"
        >
          <el-form-item label="企业Logo" prop="comp_logo">
            <el-upload
              action="http://localhost:5261/api/Company/Upload"
              list-type="picture-card"
              :auto-upload="true"
              v-model:file-list="rulelist"
              :limit="1"
              :on-exceed="handleExceed"
              ref="upload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              class="form_content"
              accept=".jpg,.png"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleDownload(file)"
                    >
                      <el-icon><Download /></el-icon>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <el-icon><Delete /></el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>
            <div class="form_content" style="color: #cccccc">
              建议上传图片大小不超过2MB，格式只能是*.jpg,*.png
            </div>
            <el-dialog v-model="dialogVisible">
              <img
                w-full
                :src="dialogImageUrl"
                alt="Preview Image"
                style="max-width: 100%; height: auto"
              />
            </el-dialog>
          </el-form-item>
          <el-form-item label="企业名称" prop="comp_name">
            <el-input
              v-model="info_Company.comp_name"
              style="width: 240px"
              class="form_content"
            />
          </el-form-item>
          <el-form-item label="企业编码" prop="comp_code">
            <el-input
              v-model="info_Company.comp_code"
              style="width: 240px"
              class="form_content"
              :disabled="codeVisible"
            />
          </el-form-item>
          <el-form-item label="联系人姓名" prop="contact_by">
            <el-input
              v-model="info_Company.contact_by"
              style="width: 240px"
              class="form_content"
            />
          </el-form-item>
          <el-form-item label="联系人电话" prop="contact_phone">
            <el-input
              v-model="info_Company.contact_phone"
              style="width: 240px"
              class="form_content"
            />
          </el-form-item>
          <el-form-item label="公司地址" prop="comp_address">
            <el-input
              v-model="info_Company.comp_address"
              style="width: 240px"
              class="form_content"
            />
          </el-form-item>
          <el-form-item label="备注信息" prop="comp_Remark">
            <el-input
              v-model="info_Company.comp_Remark"
              style="width: 240px"
              class="form_content"
            />
          </el-form-item>
          <div class="btn_div">
            <el-form-item>
              <el-button type="primary" @click="onSubmit" class="btn">保存</el-button>
              <!-- <el-button>Cancel</el-button> -->
            </el-form-item>
          </div>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>


<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getRandomString } from "@/randomString/random.js";
import { useRouter } from "vue-router";
import $http from "@/axios/base";

export default {
  name: "app",
  setup() {
    const info_Company = reactive({
      comp_id: 0,
      comp_name: "",
      comp_logo: "",
      comp_code: "",
      contact_by: "",
      contact_phone: "",
      comp_address: "",
      comp_Remark: "",
      Create_by: sessionStorage.getItem("empname"),
      Create_time: new Date().toISOString().slice(0, 10).toString(),
      update_by: "",
      update_time: "",
      Is_del: 0,
    });

    let rulelist = ref([
      {
        name: "TX.jpg",
        url: "http://localhost:5261/images/TX.jpg",
      },
    ]);

    const rules = reactive({
      comp_name: [
        {
          required: true,
          message: "企业名称不能为空！！！",
          trigger: "blur",
        },
      ],
      contact_by: [
        {
          required: true,
          message: "联系人姓名不能为空！！！",
          trigger: "blur",
        },
      ],
      contact_phone: [
        {
          required: true,
          message: "联系人电话不能为空！！！",
          trigger: "blur",
        },
        {
          pattern:
            /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/,
          message: "请输入正确的手机号码格式",
          trigger: "blur",
        },
      ],
      comp_address: [
        {
          required: true,
          message: "公司地址不能为空！！！",
          trigger: "blur",
        },
      ],
      comp_logo: [{ required: true, message: "请上传图片", trigger: "change" }],
    });

    let upload = ref(null);
    let router = useRouter();
    const form = ref(null);

    function onSubmit() {
      form.value.validate((valid) => {
        if (valid) {
          //这里可以执行提交表单的操作，比如发送请求到后端
          info_Company.update_by = sessionStorage.getItem("empname");
          info_Company.update_time = new Date()
            .toISOString()
            .slice(0, 10)
            .toString();
          $http
            .put("http://localhost:5261/api/Company/UpdCompany", info_Company)
            .then((res) => {
              if (res) {
                // ElMessage.success("添加成功！！！");
                location.reload();
                setTimeout(() => {
                  ElMessage.success("操作成功！！！");
                }, 1000);
              } else {
                ElMessage.error("操作失败！！！");
              }
            })
            .catch((err) => console.log(err));
        } else {
          //验证没有通过
          ElMessage.warning("请填写完整数据！！！");
        }
      });
    }

    const codeVisible = true;
    const dialogImageUrl = ref("");
    const dialogVisible = ref(false);
    const disabled = ref(false);

    function handleRemove(file) {
      info_Company.comp_logo = "";
      upload.value.clearFiles();
    }

    function handlePictureCardPreview(file) {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    }

    function handleDownload(file) {
      var now = new Date();

      // 获取年、月、日、时、分、秒
      var year = now.getFullYear();
      var month = now.getMonth() + 1; // 注意月份是从 0 开始的
      var day = now.getDate();
      var imageUrl = file.url;
      var link = document.createElement("a");
      link.href = imageUrl;
      link.download =
        "七尾-" + year + month + day + getRandomString(8) + ".jpg";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    const handleUploadSuccess = (response, file, fileList) => {
      // 处理上传成功的逻辑，如显示成功消息或更新UI
      console.log("上传成功", response, file, fileList);
      rulelist.url = response.result.url;
      info_Company.comp_logo = response.result.url;
    };

    const handleUploadError = (error, file, fileList) => {
      // 处理上传失败的逻辑，如显示错误消息或更新UI
      console.error("上传失败", error, file, fileList);
      ElMessage.error("上传失败，文件大小或类型不符合要求");
    };

    function handleExceed(files) {
      // 当上传的文件数量超过限制时，清空已上传的文件列表，并上传最新的文件
      upload.value.clearFiles();
      const file = files[0]; // 获取最新的文件
      file.uid = Date.now(); // 为文件生成唯一的标识符
      upload.value.handleStart(file); // 开始上传最新的文件
      upload.value.submit();
    }

    function getcode() {
      $http
        .get("http://localhost:5261/api/BH/BHGZ", {
          params: {
            prefix: "QY",
          },
        })
        .then((res) => {
          info_Company.comp_code = res;
        })
        .catch((err) => console.log(err));
    }

    function show() {
      $http
        .get("http://localhost:5261/api/Company/GetCompany")
        .then((res) => {
          info_Company.comp_id = res.comp_id;
          info_Company.comp_name = res.comp_name;
          info_Company.comp_logo = res.comp_logo;
          rulelist.value[0].url = res.comp_logo;
          info_Company.comp_code = res.comp_code;
          info_Company.contact_by = res.contact_by;
          info_Company.contact_phone = res.contact_phone;
          info_Company.comp_address = res.comp_address;
          info_Company.comp_Remark = res.comp_Remark;
        })
        .catch((err) => console.log(err));
    }

    onMounted(() => {
      getcode();
      show();
    });

    return {
      codeVisible,
      form,
      rulelist,
      router,
      rules,
      upload,
      info_Company,
      dialogImageUrl,
      dialogVisible,
      disabled,
      handleRemove,
      handlePictureCardPreview,
      handleDownload,
      onSubmit,
      handleExceed,
      handleUploadError,
      handleUploadSuccess,
      getcode,
    };
  },
};
</script>

<style scoped>
.btn{
  top: auto;
  right: 90px;
  position: fixed;
  bottom: 42px;
  z-index: 1000;
  width: 80px;
  height: 35px;
}

.btn_div {
  border-radius: 10px 10px 0px 0px;
  padding-right: 37px;
  margin-top: 20px;
  height: 80px; 
  background-color: #ffffff;
  width: 1540px;
  position: fixed;
  /* 固定位置 */
  top: auto;
  /* 距离顶部20像素 */
  right: 70px;
  /* 距离右侧20像素 */
  bottom: 20px;
  /* 底部自动 */
  left: auto;
  /* 左侧自动 */
  z-index: 1000;
  /* 确保它在其他内容之上 */
}

.el-radio-group {
  margin-right: 12px;
}
.t_div {
  margin-bottom: 20px;
  text-align: left;
  font-size: 14px;
  color: #b3b4b6;
}
a {
  text-decoration: none;
}
.f_div {
  padding: 0px 50px;
}
.h_div {
  border-bottom: 1px solid #f2f2f2;
  height: 39px;
}
.h_in_vid {
  width: 100px;
  height: 20px;
  margin-top: 20px;
  border-left: 5px solid #006eff;
}
.header {
  background-color: #ffffff;
  border-radius: 10px 10px 0px 0px;
}
.main {
  background-color: #ffffff;
  border-radius: 0px 0px 10px 10px;
  height: 560px;
}
.form_content {
  margin-left: 50px;
}
</style>